

import os
import sys
import wsgiref.handlers

from django.utils import simplejson

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users

from geo import geotypes

from models import Restaurant
from models import Comment

class GetRestaurantService(webapp.RequestHandler):
    def get(self):
        
        self.response.headers['Content-Type'] = 'application/json'
        
        restaurants = Restaurant.all()
        
        results_obj = [
            {
                'id':restaurant.key().id(),
                'name':restaurant.name,
                'address':restaurant.address,
                'author':restaurant.author.nickname(),
                'description':restaurant.description,
                'lat': restaurant.latitude,
                'lon': restaurant.longitude,
            }
            for restaurant in restaurants
        ]
        
        self.response.out.write(simplejson.dumps({
            'status': 'success',
            'results': results_obj
        }))
        
class PutRestaurantService(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-Type'] = 'application/json'
        
        if users.get_current_user() == None:
            self.response.set_status(405)
            self.response.out.write('user not logged in')
            return
                
        restaurant = Restaurant()
        restaurant.author =  users.get_current_user()
        restaurant.name = self.request.get('name');
        restaurant.address = db.PostalAddress(self.request.get('address'));

        restaurant.description = self.request.get('description');
        restaurant.latitude = float(self.request.get('lat'));
        restaurant.longitude = float(self.request.get('lon'));

        if self.request.get('phone'):
            restaurant.phone = db.PhoneNumber(self.request.get('phone'));
            
        if self.request.get('link'):
           restaurant.link = db.Link(self.request.get('link'));           
        
        if restaurant.validate():
            restaurant.put()
            self.response.out.write(simplejson.dumps({
                'status': 'success'
            }))
        else:
            self.response.out.write(simplejson.dumps({
                'status': 'error',
                'name':restaurant.name,
                'address':restaurant.address,
                'author':restaurant.author.nickname(),
                'description':restaurant.description,
                'lat': restaurant.latitude,
                'lon': restaurant.longitude,
            }))
            
# class GetImage(webapp.RequestHandler):
    # def get(self):
        # title = self.request.get('title')
        # image = getImage(title)
        # if (movie and movie.picture):
            # self.response.headers['Content-Type'] = 'image/jpeg'
            # self.response.out.write(image.picture)
        # else:
            # self.redirect('/static/noimage.jpg')
            
class GetComment(webapp.RequestHandler):
    def get(self):
        
        id = self.request.get('id')
        
        comments = Comment.gql("WHERE ANCESTOR IS :1 "
                               "ORDER BY date DESC",
                                db.Key.from_path('Restaurant', id))
        results_obj = [
            {
                'message':comment.message,
                'author':comment.author.nickname(),
                # 'date':comment.date,
                'price':comment.price,
                'quality': comment.quality,
                'quantity': comment.quantity,
            }
            for comment in comments
        ]
        
        self.response.out.write(simplejson.dumps({
            'status': 'success',
            'results': results_obj
        }))
        
class PutComment(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
        
        if users.get_current_user() == None:        
            self.response.set_status(405)
            self.response.out.write('user not logged in')
            return
       
        id = self.request.get('id')
        msg = self.request.get('msg')
        price = self.request.get('price')
        quality = self.request.get('quality')
        quantity = self.request.get('quantity')
        
        comment = Comment(parent=db.Key.from_path('Restaurant', id))
        comment.author =  users.get_current_user()
        comment.message = msg;
        comment.price = price
        comment.quality = quality
        comment.quantity = quantity

        if comment.validate():
            comment.put()
            self.response.out.write(simplejson.dumps({
                'status': 'success'
            }))
        else:
            self.response.out.write(simplejson.dumps({
                'status': 'error',
                'message':comment.message,
                'author':comment.author.nickname(),
                'price':comment.price,
                'quality': comment.quality,
                'quantity': comment.quantity,
            }))
                  
application = webapp.WSGIApplication([
    ('/r/get', GetRestaurantService),
    ('/r/put', PutRestaurantService),
    ('/c/get', GetComment),
    ('/c/put', PutComment)
    # ('/i/get', GetImage),
    ],
    debug=True)     
            

def main():    
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
